//
//  SingletonStoryboardSegue.swift
//  JKTools
//
//  Created by 姜奎 on 2024/8/29.
//

import AppKit

class SingletonStoryboardSegue: NSStoryboardSegue {
    override func perform() {
        let id = self.identifier as? NSString

        if Self.findObject(forKey: id) != nil {
            return
        }

        super.perform()

        Self.setObject(self.destinationController as AnyObject, forKey: id)
    }

    static let objects: NSMapTable<NSString, AnyObject> = NSMapTable<NSString, AnyObject>.strongToWeakObjects()

    static func findObject(forKey aKey: NSString?) -> AnyObject? {
        guard let aKey = aKey else { return nil }
        return self.objects.object(forKey: aKey)
    }

    static func setObject(_ object: AnyObject?, forKey aKey: NSString?) {
        guard let object = object, let aKey = aKey else { return }
        self.objects.setObject(object, forKey: aKey)
    }
}
